/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pz.util;

import java.nio.ByteBuffer;
import java.util.ArrayList;

/**
 *
 * @author jannek
 */
public class MessageMannager {

    private static final MessageMannager instance;
    
//    public static final byte SEND = 1;
//    public static final byte HELLO = 2;
//    public static final byte WELCOME = 3;
//    public static final byte CONFIRM = 4;
//    public static final byte PING = 5;
//    public static final byte PONG = 6;
//    public static final byte ISEEYOU = 7;
//    public static final byte BYE = 8;
//    public static final byte DISCONNECT_USER = 9;
//    public static final byte DISCONNECT_KICK = 10;
//    public static final byte DISCONNECT_CLOSE = 11;
    public static final int MAX_LENGHT = 500;
//    public static final int MAX_LENGHT_TOTAL = 512;
    private final ArrayList<ByteBuffer> available;

    static {
        instance = new MessageMannager();
    }

    public static MessageMannager getMannager() {
        return instance;
    }

    private MessageMannager() {
        available = new ArrayList<ByteBuffer>(50);
    }

    public ByteBuffer get(ByteBuffer data) {
        synchronized (available) {
            if (available.isEmpty())
                return ByteBuffer.allocate(MAX_LENGHT).put(data);
            return ((ByteBuffer) available.remove(available.size() - 1).
                    clear()).put(data);
        }
    }

    public ByteBuffer get() {
        synchronized (available) {
            if (available.isEmpty())
                return ByteBuffer.allocate(MAX_LENGHT);
            return (ByteBuffer) available.remove(available.size() - 1).clear();
        }
    }

    public void dispose(ByteBuffer message) throws RuntimeException {
        if (message.capacity() != MAX_LENGHT)
            throw new RuntimeException("Not a message. Wrong capacity.");
        synchronized (available) {
            available.add(message);
        }
    }
}
